#include "chat1.h"
#include "ui_chat1.h"
#include <QMessageBox>
#include <QDebug>
#include "login.h"
#include "ui_login.h"
#include "tiren.h"
#include "ui_tiren.h"
#include "jinyan.h"
#include "ui_jinyan.h"
#include "jiejin.h"
#include "ui_jiejin.h"
#include "wenjian.h"
#include "ui_wenjian.h"
#include <QFile>

QPushButton *selectedButton = nullptr;

chat1::chat1(const QString &username, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::chat1),
    m_username(username),
    flag("0")
{
    ui->setupUi(this);
    socket = new QTcpSocket(this);

    connect(socket, &QTcpSocket::connected, this, &chat1::onConnected);
    connect(socket, &QTcpSocket::readyRead, this, &chat1::onReadyRead);
    connect(socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this, &chat1::onError);

    socket->connectToHost("192.168.159.131", 1234);

    // 创建“群聊”按钮
    QPushButton *groupChatButton = new QPushButton("群聊", this);
    connect(groupChatButton, &QPushButton::clicked, [=]() {
        // 判断是否有选定的按钮，并将其颜色恢复默认
        if (selectedButton != nullptr) {
            selectedButton->setStyleSheet(""); // 将样式表设置为空，恢复默认颜色
        }

        ui->stackedWidget->setCurrentWidget(ui->page_2); // 切换到 page_2 页面

        // 设置当前按钮为选定状态，修改样式为蓝色
        selectedButton = groupChatButton;
        groupChatButton->setStyleSheet("background-color: blue; color: white;");
    });

    // 获取 QListWidget 对象
    QListWidget *listWidget = ui->listWidget;

    // 添加按钮到 QListWidget 中
    QListWidgetItem *item = new QListWidgetItem(listWidget);
    listWidget->setItemWidget(item, groupChatButton);
}

chat1::~chat1()
{
    delete ui;
}

void chat1::on_people_clicked()
{
    QString message = "PEOPLE\nNONE\n";
    socket->write(message.toUtf8());

    qDebug() << "发送信息";
}

void chat1::on_close_clicked()
{
    QString message = "CLOSE2\n";
    message += m_username + "\n";
    socket->write(message.toUtf8());

    qDebug() << "发送信息";
}

void chat1::onConnected() {
    qDebug() << "已连接到服务器！";
    QString message = "LOGIN_IN\n";
    message += m_username + "\n";
    socket->write(message.toUtf8());
}

void chat1::onReadyRead() {
    QByteArray data = socket->readAll();

    QDataStream stream(&data, QIODevice::ReadOnly);
    QString message;
    stream >> message;
    qDebug() << message;

    int spaceIndex = message.indexOf('\n'); // 寻找第一个空格的位置

    QString responseType = message.left(spaceIndex);
    QString Data = message.mid(spaceIndex + 1);

    qDebug() << "接收信息";

    if (responseType == "PEOPLE") {
        Data += "人";
        QMessageBox::information(this, "在线人数", Data);
    } else if (responseType == "CLOSE2") {
        login *newWidget = new login();  // 创建新窗口对象
        newWidget->show();  // 显示新窗口
        this->close();  // 关闭当前窗口
    } else if (responseType == "LOGIN_IN") {
        addClientPage(Data);
    } else if (responseType == "LOGIN_IN2") {
        QStringList userNamesList = Data.split("\n");
        for (const QString& userName : userNamesList) {
            if (userName != "") {
                addClientPage(userName);
            }
        }
    } else if (responseType == "CLOSE") {
        deleteClientPage(Data);
    } else if (responseType == "CHAT2") {
        QStringList parts = Data.split("\n", QString::SkipEmptyParts);
        QString username = parts[0];
        QString message = "[" + username + "]: " + parts[1];
        QString username1 = username + "1";

        qDebug() << username << message;

        QWidget* page = ui->stackedWidget->findChild<QWidget*>(username);

        if (page) {
            // 找到页面后，查找该页面中的 textEdit1
            QTextEdit* textEdit1 = page->findChild<QTextEdit*>(username1);

            if (textEdit1) {
                // 如果找到 textEdit1，则将消息添加到其中
                textEdit1->append(message);
            } else {
                // 如果未找到 textEdit1
                qDebug() << "未找到 textEdit1";
            }
        } else {
             // 如果未找到页面
             qDebug() << "未找到页面";
        }
    } else if (responseType == "CHAT1") {
        QStringList parts = Data.split("\n", QString::SkipEmptyParts);
        QString username = parts[0];
        QString message = "[" + username + "]: " + parts[1];

        qDebug() << username << message;

        QWidget* page = ui->stackedWidget->findChild<QWidget*>("page_2");

        if (page) {
            // 找到页面后，查找该页面中的 textEdit
            QTextEdit* textEdit = page->findChild<QTextEdit*>("textEdit");

            if (textEdit) {
                // 如果找到 textEdit，则将消息添加到其中
                textEdit->append(message);
            } else {
                // 如果未找到 textEdit
                qDebug() << "未找到 textEdit";
            }
        } else {
             // 如果未找到页面
             qDebug() << "未找到页面";
        }
    } else if (responseType == "TIREN_SUCCESS") {
        tiren *newWidget = new tiren();  // 创建新窗口对象
        newWidget->show();  // 显示新窗口
    } else if (responseType == "TIREN_FAIL") {
        QMessageBox::warning(this, "提示", "您不是群主");
    } else if (responseType == "JINYAN_SUCCESS") {
        jinyan *newWidget = new jinyan();  // 创建新窗口对象
        newWidget->show();  // 显示新窗口
    } else if (responseType == "JINYAN_FAIL") {
        QMessageBox::warning(this, "提示", "您不是群主");
    } else if (responseType == "JIEJIN_SUCCESS") {
        jiejin *newWidget = new jiejin();  // 创建新窗口对象
        newWidget->show();  // 显示新窗口
    } else if (responseType == "JIEJIN_FAIL") {
        QMessageBox::warning(this, "提示", "您不是群主");
    } else if (responseType == "TIREN2") {
        QMessageBox::information(this, "提示", "您已被群主踢出");
        login *newWidget = new login();  // 创建新窗口对象
        newWidget->show();  // 显示新窗口
        this->close();  // 关闭当前窗口
    } else if (responseType == "JINYAN2") {
        QMessageBox::information(this, "提示", "您已被群主禁言");
        flag = "1";
    } else if (responseType == "JIEJIN2") {
        QMessageBox::information(this, "提示", "您已被群主解禁");
        flag = "0";
    } else if (responseType == "WENJIAN") {
        QString filename = "../" + Data;
        QString file1;
        stream >> file1;
        QFile file(filename);
        if (!file.open(QIODevice::WriteOnly)) {
            qDebug() << "创建文件失败";
            return;
        }

        // 写入数据到文件
        file.write(file1.toUtf8());
        file.close();
        QMessageBox::information(this, "提示", "已接收文件：" + Data);
    }
}

void chat1::onError(QAbstractSocket::SocketError socketError) {
    qDebug() << "Socket错误:" << socketError;
}

void chat1::closeEvent(QCloseEvent *event) {
    // 发送关闭消息给服务器
    qDebug() << "关闭客户端";
    QString message = "CLOSE\n";
    message += m_username + "\n";
    socket->write(message.toUtf8());

    QWidget::closeEvent(event);
    emit closed();
}

void chat1::addClientPage(const QString& username) {
    // 创建新页面
    QWidget* newPage = new QWidget();
    newPage->setObjectName(username);
    ui->stackedWidget->addWidget(newPage);

    QString username1 = username + "1";

    // 创建页面内的部件
    QTextEdit* textEdit1 = new QTextEdit(newPage);
    QTextEdit* textEdit2 = new QTextEdit(newPage);
    QPushButton* sendButton = new QPushButton("发送", newPage);
    QPushButton* clearButton = new QPushButton("清空", newPage);

    // 设置部件的位置和大小
    textEdit1->setGeometry(30, 20, 341, 241);
    textEdit1->setReadOnly(true);
    textEdit1->setObjectName(username1);
    textEdit2->setGeometry(30, 280, 341, 91);
    sendButton->setGeometry(70, 390, 89, 25);
    clearButton->setGeometry(230, 390, 89, 25);

    connect(sendButton, &QPushButton::clicked, [=]() {
        if (flag=="1") {
            QMessageBox::information(this, "提示", "您已被群主禁言");
        } else {
            // 获取textEdit2的内容
            QString message = textEdit2->toPlainText();
            // 合并为完整消息
            QString fullMessage = "[" + m_username + "]: " + message;

            // 添加消息到textEdit1中
            textEdit1->append(fullMessage);

            // 清空textEdit2内容
            textEdit2->clear();

            QString Message = "CHAT2\n";
            Message += username + "\n" + message + "\n" + m_username + "\n";
            socket->write(Message.toUtf8());
        }
    });

    connect(clearButton, &QPushButton::clicked, [=]() {
        textEdit2->clear();
    });

    // 在 listWidget 中添加一个新按钮
    QPushButton* clientButton = new QPushButton(username, this);
    connect(clientButton, &QPushButton::clicked, [=]() {
        // 判断是否有选定的按钮，并将其颜色恢复默认
        if (selectedButton != nullptr) {
           selectedButton->setStyleSheet(""); // 将样式表设置为空，恢复默认颜色
        }

        ui->stackedWidget->setCurrentWidget(newPage);

        // 设置当前按钮为选定状态，修改样式为蓝色
        selectedButton = clientButton;
        clientButton->setStyleSheet("background-color: blue; color: white;");
    });

    QListWidgetItem* item = new QListWidgetItem(ui->listWidget);
    ui->listWidget->addItem(item);
    ui->listWidget->setItemWidget(item, clientButton);
}

void chat1::deleteClientPage(const QString& username) {
    // 遍历 QListWidget 中的每一个 item
    for (int i = 0; i < ui->listWidget->count(); ++i) {
        QListWidgetItem* item = ui->listWidget->item(i);
        QPushButton* button = qobject_cast<QPushButton*>(ui->listWidget->itemWidget(item));

        if (button && button->text() == username) {
            ui->listWidget->takeItem(i); // 从 QListWidget 中移除按钮

            // 获取页面并移除
            QWidget* pageToRemove = nullptr;
            for (int j = 0; j < ui->stackedWidget->count(); ++j) {
                QWidget* page = ui->stackedWidget->widget(j);
                if (page->objectName() == username) {
                    pageToRemove = page;
                    break;
                }
            }

            if (pageToRemove) {
                ui->stackedWidget->removeWidget(pageToRemove); // 从 stackedWidget 中移除页面
                delete pageToRemove; // 删除页面
            }

            break; // 找到并删除后，退出循环
        }
    }
}

void chat1::on_pushButton_4_clicked()
{
    QWidget* page = ui->stackedWidget->findChild<QWidget*>("page_2");

    if (page) {
        // 找到页面后，查找该页面中的 textEdit2
        QTextEdit* textEdit2 = page->findChild<QTextEdit*>("textEdit_2");

        if (textEdit2) {
            // 如果找到 textEdit2
            textEdit2->clear();
        } else {
            // 如果未找到 textEdit2
            qDebug() << "未找到 textEdit2";
        }
    } else {
         // 如果未找到页面
         qDebug() << "未找到页面";
    }
}

void chat1::on_pushButton_3_clicked()
{
    if (flag=="1"){
        QMessageBox::information(this, "提示", "您已被群主禁言");
    } else {
        QWidget* page = ui->stackedWidget->findChild<QWidget*>("page_2");

        if (page) {
            // 找到页面后，查找该页面中的 textEdit,textEdit2
            QTextEdit* textEdit = page->findChild<QTextEdit*>("textEdit");
            QTextEdit* textEdit2 = page->findChild<QTextEdit*>("textEdit_2");

            // 获取textEdit2的内容
            QString message = textEdit2->toPlainText();
            // 合并为完整消息
            QString fullMessage = "[" + m_username + "]: " + message;

            // 添加消息到textEdit中
            textEdit->append(fullMessage);

            // 清空textEdit2内容
            textEdit2->clear();

            QString Message = "CHAT1\n";
            Message += message + "\n" + m_username + "\n";
            socket->write(Message.toUtf8());

        } else {
             // 如果未找到页面
             qDebug() << "未找到页面";
        }
    }
}

void chat1::on_wenjian_clicked()
{
    wenjian *newWidget = new wenjian();  // 创建新窗口对象
    newWidget->show();  // 显示新窗口
}

void chat1::on_tiren_clicked()
{
    QString message = "TIREN\n";
    message += m_username + "\n";
    socket->write(message.toUtf8());

    qDebug() << "发送信息";
}

void chat1::on_jinyan_clicked()
{
    QString message = "JINYAN\n";
    message += m_username + "\n";
    socket->write(message.toUtf8());

    qDebug() << "发送信息";
}

void chat1::on_jiejin_clicked()
{
    QString message = "JIEJIN\n";
    message += m_username + "\n";
    socket->write(message.toUtf8());

    qDebug() << "发送信息";
}
